﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;

namespace Urd.Common
{
    /// <summary>
    /// сделать кеширование из sqlite :memory: готово
    /// для позиций и ротаций.
    /// одна таблица для позиций другая для ротаций. переделать менеджер в инстансируемый класс.
    /// </summary>
   

    public class cache:IDisposable
    {
        SQLiteConnection scon;
        object lockobject;
        DateTime timestart;
        DateTime timefinish;
        TimeSpan timespan;
        DataSet ds;
        public cache()
        {
            lockobject = new object();
            scon = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;");
            scon.Open();
            
        }
       
        public void close() 
        {
            if(scon!=null)
            scon.Close();
        }

        public object[] Sql(string request, bool read)
        {
            lock (lockobject)
            {
                timestart = DateTime.Now;
                List<object> ret = new List<object>();  

                    if (read)
                    {
                       try
                       {
                            SQLiteCommand scom = new SQLiteCommand(scon);
                            scom.CommandText = request;  
                            SQLiteDataReader dr = scom.ExecuteReader();
                            int count = dr.FieldCount;
                            object[] temp = new object[count];
                        while (dr.HasRows)
                        {
                            while (dr.Read())
                            {
                                dr.GetValues(temp);
                                ret.AddRange(temp);
                            }
                            dr.NextResult();
                            
                        }
                        dr.Close();
                           timefinish = DateTime.Now;
                           timespan = timefinish - timestart;  
                            debug.Log("[cache][done]("+timespan.ToString()+"):" + request,debug.loglevel.Status);
                        }
                        catch (SQLiteException e) { debug.Log("[cache][read][sqlite]:" + e.Source + " " + e.Message, debug.loglevel.Errors); }
                        catch (Exception e) { debug.Log("[cache][read][system]:" + e.Source + " " + e.Message, debug.loglevel.Errors);  }
                    }
                    else
                    {
                        try
                        {
                           
                            SQLiteCommand scom = new SQLiteCommand(scon);
                            scom.CommandText = request;
                            ret.Add(scom.ExecuteNonQuery());
                            timefinish = DateTime.Now;
                            timespan = timefinish - timestart;
                            debug.Log("[cache][done](" + timespan.ToString() + "):" + request, debug.loglevel.Status);
                        }
                        catch (SQLiteException e) { debug.Log("[cache][non query][sqlite]:" + e.Source + " " + e.Message, debug.loglevel.Errors); }
                        catch (Exception e) { debug.Log("[cache]][non query[system]:" + e.Source + " " + e.Message, debug.loglevel.Errors);  }
                    }           
                return ret.ToArray();
            }
        }
        public void DumpTable(string filename)
        {
            try
            {
                SQLiteConnection con = new SQLiteConnection("Data Source=" + filename + ";Version=3;New=True;");
                con.Open();
                scon.BackupDatabase(con, "main", "main", -1, null, -1);
                con.Close();
            }
            finally
            { }
        }
        public long MemoryUsed { get { return scon.MemoryUsed; } }
        public SQLiteConnection Connection { get { return scon; } }
        public DataSet dataset { get { return ds; } set { ds = value; } }
        public void Dispose() { scon.Dispose(); }
    }
}
